package com.reason.pay.service.impl;

import com.reason.pay.service.WXPayService;
import com.github.wxpay.sdk.WXPay;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 陈正果
 * @date 2020/06/30 1:08
 */
@Service
public class WXPayServiceImpl implements WXPayService {

    //获取配置文件中微信回调地址
    @Value("${wxpay.notify_url}")
    private String notify_url;

    @Autowired
    private WXPay wxPay;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 微信支付下单服务
     *
     * @param orderId  订单id
     * @param payMoney 支付金额
     * @return 微信下单结果
     */
    @Override
    public Map<String, String> nativePay(String orderId, String payMoney) {
        try {

            //定义传输参数
            Map<String, String> sendMessage = new HashMap<>();

            sendMessage.put("body", "缘来是你会员");
            //订单id
            sendMessage.put("out_trade_no", orderId);

//            BigDecimal Money = new BigDecimal(payMoney);

            //支付金额，固定为1分钱( '分' 为单位)
            BigDecimal money = new BigDecimal(payMoney);
            //支付金额 *100
            BigDecimal money_fen = money.multiply(new BigDecimal("100"));
            //支付金额保留整数
            money_fen = money_fen.setScale(0, BigDecimal.ROUND_UP);
            sendMessage.put("total_fee", String.valueOf(money_fen));
            //终端IP
            sendMessage.put("spbill_create_ip", "127.0.0.1");
            //通知地址
            sendMessage.put("notify_url", notify_url);
            //交易类型
            sendMessage.put("trade_type", "NATIVE");

            Map<String, String> resultMap = wxPay.unifiedOrder(sendMessage);

            System.out.println(resultMap);

            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查询微信支付信息
     *
     * @param orderId 商户订单id
     * @return 微信支付信息结果
     */
    @Override
    public Map<String, String> queryOrder(String orderId) {
        try {
            Map<String, String> reqData = new HashMap<>();
            reqData.put("out_trade_no", orderId);
            return wxPay.orderQuery(reqData);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
